﻿using Hydrogen.ULib.Attributes;
using System;
using System.Collections.Generic;
using System.Xml;

namespace Hydrogen.MarkovChain
{
    [RuleNodeName(RuleConstant.NODE_SEQUENCE), Serializable]
    public class RuleSequence : RuleNodeBase, IRuleNodeExcuteable
    {
        /// <summary>
        /// 子节点类型
        /// </summary>
        private static List<string> _chileNodeTypes = new List<string>()
        {
            RuleConstant.NODE_MK,
        };

        [UnityEngine.SerializeField, ReadOnly]
        private List<RuleNodeBase> _children;

        /// <summary>
        /// 使用次数，-1为无限次使用.<br/>
        /// 执行失败时-1
        /// </summary>
        private int _life = -1;

        public RuleSequence(XmlNode xmlNode) : base(xmlNode)
        {
            this._children = GetChildNode(xmlNode, _chileNodeTypes);
            if (!int.TryParse(xmlNode.GetAttributeValue(RuleConstant.SEQUENCE_LIFE), out this._life)) this._life = -1;
        }

        public override void Reset()
        {
            base.Reset();
            foreach (RuleNodeBase childNode in this._children) childNode.Reset();
        }

        public bool TryExcute(Func<IRuleNodeSolidReplace, bool> excuteAcvive)
        {
            if (this._life == 0) return false;
            foreach (var item in this._children)
            {
                if (item is RuleMK)
                {
                    if (!(item as RuleMK).TryExcute(excuteAcvive)) continue;
                    return true;
                }
            }

            this._life--;
            return false;
        }
    }
}